package com.ruoyi.system.controller;

import java.io.IOException;
import java.util.List;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.DocDocument;
import com.ruoyi.system.domain.DocCategory;
import com.ruoyi.system.service.IDocDocumentService;
import com.ruoyi.system.service.IDocCategoryService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.StringUtils;
import org.apache.commons.io.FilenameUtils;

/**
 * 文档Controller
 * 
 * @author ruoyi
 * @date 2023-07-25
 */
@Controller
@RequestMapping("/system/document")
public class DocDocumentController extends BaseController
{
    private String prefix = "system/document";

    @Autowired
    private IDocDocumentService docDocumentService;
    
    @Autowired
    private IDocCategoryService docCategoryService;

    @RequiresPermissions("system:document:view")
    @GetMapping()
    public String document()
    {
        return prefix + "/document";
    }

    /**
     * 查询文档列表
     */
    @RequiresPermissions("system:document:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(DocDocument docDocument)
    {
        startPage();
        List<DocDocument> list = docDocumentService.selectDocDocumentList(docDocument);
        return getDataTable(list);
    }

    /**
     * 导出文档列表
     */
    @RequiresPermissions("system:document:export")
    @Log(title = "文档", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(DocDocument docDocument)
    {
        List<DocDocument> list = docDocumentService.selectDocDocumentList(docDocument);
        ExcelUtil<DocDocument> util = new ExcelUtil<DocDocument>(DocDocument.class);
        return util.exportExcel(list, "文档数据");
    }

    /**
     * 新增文档
     */
    @RequiresPermissions("system:document:add")
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        // 获取所有文档分类列表
        List<DocCategory> categories = docCategoryService.selectDocCategoryList(new DocCategory());
        mmap.put("categories", categories);
        return prefix + "/add";
    }

    /**
     * 新增保存文档
     */
    @RequiresPermissions("system:document:add")
    @Log(title = "文档", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(DocDocument docDocument, @RequestParam("file") MultipartFile file)
    {
        try
        {
            // 上传文件
            if (!file.isEmpty())
            {
                String filePath = FileUploadUtils.upload(RuoYiConfig.getUploadPath(), file);
                docDocument.setFilePath(filePath);
                docDocument.setFileName(file.getOriginalFilename());
                docDocument.setFileSize(file.getSize());
                
                // 获取文件扩展名作为文件类型，而不是使用完整的MIME类型
                String extension = FilenameUtils.getExtension(file.getOriginalFilename());
                docDocument.setFileType(extension != null ? extension.toLowerCase() : "unknown");
            }
            
            return toAjax(docDocumentService.insertDocDocument(docDocument));
        }
        catch (IOException e)
        {
            return error(e.getMessage());
        }
    }

    /**
     * 修改文档
     */
    @RequiresPermissions("system:document:edit")
    @GetMapping("/edit/{documentId}")
    public String edit(@PathVariable("documentId") Long documentId, ModelMap mmap)
    {
        DocDocument docDocument = docDocumentService.selectDocDocumentByDocumentId(documentId);
        mmap.put("docDocument", docDocument);
        
        // 获取所有文档分类列表
        List<DocCategory> categories = docCategoryService.selectDocCategoryList(new DocCategory());
        mmap.put("categories", categories);
        
        return prefix + "/edit";
    }

    /**
     * 修改保存文档
     */
    @RequiresPermissions("system:document:edit")
    @Log(title = "文档", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(DocDocument docDocument, @RequestParam(value = "file", required = false) MultipartFile file)
    {
        try
        {
            // 上传新文件（如果有）
            if (file != null && !file.isEmpty())
            {
                String filePath = FileUploadUtils.upload(RuoYiConfig.getUploadPath(), file);
                docDocument.setFilePath(filePath);
                docDocument.setFileName(file.getOriginalFilename());
                docDocument.setFileSize(file.getSize());
                
                // 获取文件扩展名作为文件类型，而不是使用完整的MIME类型
                String extension = FilenameUtils.getExtension(file.getOriginalFilename());
                docDocument.setFileType(extension != null ? extension.toLowerCase() : "unknown");
            }
            
            return toAjax(docDocumentService.updateDocDocument(docDocument));
        }
        catch (IOException e)
        {
            return error(e.getMessage());
        }
    }

    /**
     * 删除文档
     */
    @RequiresPermissions("system:document:remove")
    @Log(title = "文档", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(docDocumentService.deleteDocDocumentByDocumentIds(ids));
    }
    
    /**
     * 获取文档分类列表
     */
    @RequiresPermissions("system:document:list")
    @GetMapping("/categories")
    @ResponseBody
    public AjaxResult getCategories()
    {
        List<DocCategory> categories = docCategoryService.selectDocCategoryList(new DocCategory());
        return AjaxResult.success(categories);
    }
}
